package fons.navigator.ui.windows.messages;

import java.io.IOException;
import java.util.List;

import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;

import com.google.common.collect.Lists;

public class MessagesWindow extends AppenderSkeleton {
	private JInternalFrame window;
	private HTMLEditorKit editorKit;
	private HTMLDocument document;
	
	private final List<LoggingEvent> oldEvents = Lists.newArrayList();
	
	public MessagesWindow () {
	}
	
	public JInternalFrame getWindow() {
		if (window == null) {
			window = new JInternalFrame("Meldungen", true, true, true, true);
			window.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
			
			final JTextPane messages = new JTextPane();
			final JScrollPane scrollPane = new JScrollPane(messages);
			
			messages.setAutoscrolls(true);
			messages.setEditable(false);
			messages.setEditorKit(editorKit = new HTMLEditorKit());
			document = (HTMLDocument) editorKit.createDefaultDocument();
			messages.setDocument(document);
			
			try {
				editorKit.insertHTML(document, 0, "<HTML>" +
						"<HEAD><STYLE type=\"text/css\">" +
						"td.level { font-weight: bold; width: 50px; text-align: left; }" +
						"td.time { font-size: small; width: 50px; text-align: left; }" +
						".FATAL { color: #E00000; }" +
						".ERROR { color: #E00000; }" +
						".WARN { color: #D08000; } " +
						".INFO { color: #101010; }" +
						".DEBUG { color: #0010E0; }" +
						"</STYLE></HEAD>" +
						"<BODY><h1>Meldungen</h1><table id=\"messages\"></table></BODY></HTML>",
						0, 0, null);
				
			} catch (BadLocationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
			for (LoggingEvent event: oldEvents) {
				append(event);
			}
			oldEvents.clear();			
			window.add(scrollPane);
		}
		return window;
	}
	
	@Override
	protected void append(LoggingEvent event) {
		if (window != null) {
			try {
				document.insertBeforeEnd(document.getElement("messages"), getLayout().format(event));
				
			} catch (BadLocationException e) {
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} else {
			oldEvents.add(event);
		}
	}

	@Override
	public void close() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean requiresLayout() {
		return true;
	}
}
